var fs = require('fs');
var path = require('path');
let fileInfoList = []

const DIRPATH = "freedom" + path.sep + "upload" + path.sep;


let getFileinfos = function (filePath) {
  let stat = fs.statSync(filePath)
  let fileInfo

  if (stat.isDirectory()) {
    var fileTmpInfos = fs.readdirSync(filePath);
    for (let i = 0; i < fileTmpInfos.length; i++) {
      let v = filePath + fileTmpInfos[i]
      let data = fs.statSync(v)
      if (data.isDirectory()) {
        getFileinfos(v + path.sep)
      } else {
        fileInfo = {filePath: v, stats: data}
        fileInfoList.push(getFile(fileInfo))
      }
    }
  } else {
    fileInfo = {filePath: genPath, stats: stat}
    fileInfoList.push(getFile(fileInfo))
  }

  return fileInfoList

}

let getFileInfo = function (filePath) {
  let fileTmpInfos = fs.readdirSync(filePath);
  for (let i = 0; i < fileTmpInfos.length; i++) {

  }
}


let getFile = function (value) {

  let data = {
    valueof: value.stats.ctime.valueOf(),
    file_name: value.filePath,
    file_size: value.stats.size,
    file_latest_ch: value.stats.ctime.toLocaleString(),
    isDir: value.stats.isDirectory()
  }

  return data
}

let getGenFiles = function (filePath) {
  fileInfoList = []
  let files = fs.readdirSync(filePath)
  let filesInfo = []

  for (let i = 0; i < files.length; i++) {
    let v = filePath + files[i] + path.sep
    let stats = fs.statSync(v)
    let isDIr = stats.isDirectory()
    let size = stats.size
    if (isDIr) {
      let checkFiles = getFileinfos(v + path.sep)
      for (let j = 0; j < checkFiles.length; j++) {
        size += checkFiles[j].file_size
      }
    }

    filesInfo[i] = {
      valueof: stats.ctime.valueOf(),
      file_name: files[i],
      file_path: v,
      file_size: size,
      file_latest_ch: stats.ctime.toLocaleString(),
      isDir: isDIr
    }
  }

  filesInfo.sort(function (v1, v2) {
    return v1.valueof < v2.valueof
  })

  return {file_info: filesInfo, gen_path: filePath}
}


var getFilePath = function (filePath) {
  var pp = path.resolve(__dirname, '..');
  return pp + path.sep + filePath;
}

let reset = function () {
  fileInfoList = []
}

module.exports.getFileinfos = getFileinfos;
module.exports.getFilePath = getFilePath;
module.exports.reset = reset;
module.exports.getGenFiles = getGenFiles
